package com.sky.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Map;

/**
 * 发送请求工具类
 */
public class HttpClientUtils {

    public static String DoGet(String url) {
        return DoGet(url, null);
    }

    /**
     * 发送Get请求
     *
     * @param url
     * @param params
     * @return
     */
    public static String DoGet(String url, Map<String, String> params) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "";
        try {
            URIBuilder uriBuilder = new URIBuilder(url);
            if (params != null) {
                for (String key : params.keySet()) {
                    uriBuilder.addParameter(key, params.get(key));
                }
            }
            URI uri = uriBuilder.build();
            HttpGet httpGet = new HttpGet(uri);
            response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    /**
     * 发送Post请求携带Form Data 类型参数
     *
     * @param url
     * @param params
     * @return
     */
    public static String DoPostByFormData(String url, Map<String, String> params) {
        // 1. 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";

        // 2. 定义 response 对象
        CloseableHttpResponse response = null;


        // 3. 构建Url对象和入参并发送请求
        try {
            URIBuilder uriBuilder = new URIBuilder(url);
            URI uri = uriBuilder.build();
            HttpPost httpPost = new HttpPost(uri);

            if (params != null) {
                ArrayList<NameValuePair> pairs = new ArrayList<>();
                params.forEach((key, value) -> {
                    BasicNameValuePair pair = new BasicNameValuePair(key, value);
                    pairs.add(pair);
                });
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, StandardCharsets.UTF_8);
                httpPost.setEntity(entity);
            }
            response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        return result;
    }

    /**
     * 发送Post请求携带 JSON 参数
     *
     * @param url
     * @param params
     * @return
     */
    public static String DoPostByJson(String url, Map<String, Object> params) {
        // 1. 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";

        CloseableHttpResponse respone = null;

        try {
            URIBuilder uriBuilder = new URIBuilder(url);
            URI uri = uriBuilder.build();
            HttpPost httpPost = new HttpPost(uri);
            JSONObject jsonObject = new JSONObject();
            if (params != null) {
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    jsonObject.put(entry.getKey(), entry.getValue());
                }
                StringEntity stringEntity = new StringEntity(jsonObject.toString(), StandardCharsets.UTF_8);
                stringEntity.setContentEncoding("utf-8");
                stringEntity.setContentType("application/json");

                httpPost.setEntity(stringEntity);
            }
            respone = httpClient.execute(httpPost);

            if (respone.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(respone.getEntity(), StandardCharsets.UTF_8);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (respone != null) {
                    respone.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

}
